<!DOCTYPE html>
<html>
<head>
	<title>FakeRest 服务器测试</title>
</head>
<body>
<h1>FakeRest 示例</h1>
<p>参阅示例的源代码，查看 FakeRest 用法。</p>
<h2>测试数据</h2>
<pre>
{
    'authors': [
        { id: 0, first_name: 'Leo', last_name: 'Tolstoi' },
        { id: 1, first_name: 'Jane', last_name: 'Austen' }
    ],
    'books': [
        { id: 0, author_id: 0, title: 'Anna Karenina' },
        { id: 1, author_id: 0, title: 'War and Peace' },
        { id: 2, author_id: 1, title: 'Pride and Prejudice' },
        { id: 3, author_id: 1, title: 'Sense and Sensibility' }
    ]
}
</pre>
<div>
	<h2>GET /authors</h2>
	<textarea id="req1" cols=80 rows=3></textarea>
</div>
<div>
	<h2>GET /books/3</h2>
	<textarea id="req2" cols=80 rows=1></textarea>
</div>
<div>
	<h2>POST /books { author_id: 1, title: 'Emma' }</h2>
	<textarea id="req3" cols=80 rows=1></textarea>
</div>
<script src="./FakeRest.min.js"></script>
<script src="./client-bundle.js"></script>
<script type="text/javascript">
// 初始化一个伪造的 Rest Server
var restServer = new FakeRest.FetchServer('http://fakeapi');
// 为 Rest Server 提供数据
restServer.init({
    'authors': [
        { id: 0, first_name: 'Leo', last_name: 'Tolstoi' },
        { id: 1, first_name: 'Jane', last_name: 'Austen' }
    ],
    'books': [
        { id: 0, author_id: 0, title: 'Anna Karenina' },
        { id: 1, author_id: 0, title: 'War and Peace' },
        { id: 2, author_id: 1, title: 'Pride and Prejudice' },
        { id: 3, author_id: 1, title: 'Sense and Sensibility' }
    ]
});
// 打印 fetch 日志，它默认是关闭的
restServer.toggleLogging();

// 使用 restServer 作为 fetch mock
fetchMock.mock(/^http\:\/\/fakeapi/, restServer.getHandler())

// 现在查询这个伪造的 REST server
fetch('http://fakeapi/authors?range=%5B0,1%5D')
    .then(res => res.text())
    .then(res => document.getElementById('req1').value = res);

fetch('http://fakeapi/books/3')
    .then(res => res.text())
    .then(res => document.getElementById('req2').value = res);

fetch('http://fakeapi/books', {
        method: 'POST',
        body: JSON.stringify({ author_id: 1, title: 'Emma' })
    })
    .then(res => res.text())
    .then(res => document.getElementById('req3').value = res);

// 恢复原生 fetch 功能
fetchMock.restore();
</script>
</body>
</html>
